package com.iot.mqtt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.iot.ruler.core.Ruler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * MQTT消息回调处理
 *
 * @author lzb22
 */
@Component
@Slf4j
public class MqttMsgRules extends Ruler<MessageCallBackSubject, String, String> {
    @Override
    public String getTag() {
        return "MQTT消息转发Ruler";
    }

    @Override
    public boolean condition(MessageCallBackSubject event) {
        return true;
    }

    @Override
    public void apply(MessageCallBackSubject event) {
        try {
            String topic = event.getTopic();
            String messageStr = (String) event.getSource();
            int qos = event.getQos();
            log.info("{}-{},主题：{}，QOS:{}，size：{}", getTag(), DateUtil.now(), topic, qos, messageStr.getBytes().length);

            if (!JSONUtil.isTypeJSON(messageStr)) {
                log.info("topic:{},message=======>\n{}", topic, messageStr);
                log.info("=======================>");
                throw new RuntimeException("错误的JSON格式");
            }

            JSONObject body = JSON.parseObject(messageStr);
            if (body.isEmpty()) {
                throw new Exception("Data receiver：data is empty！");
            }
            log.info("topic:{},message=======>\n{}", topic, body);
            if (topic.startsWith("Data/")) {
                // 模型数据信息处理
                publisher.publish(new DataMessageReceiveSubject(body));
            } else {
                log.warn("未知主题: {}, 内容: {}", topic, body);
            }
        } catch (Exception e) {
            log.error("处理错误{}", e.getMessage());
        }
    }

    @Override
    public void publish(String message) {

    }
}
